<?php
use think\Db;
use think\facade\Env;
use \PHPQRCode\QRcode;
/**
 * 接口返回json
 * @method apiReturn
 * @author chengzhigang
 * @return msg 提示信息 code(0成功 1失败 2重新登录) data 返回数据 time 请求时间
 */
function apiReturn($msg = "", $code = 1, $data = "")
{
    $result = array(
        'code' => $code,
        'msg' => $msg,
        'data' => $data,
        'time' => date('Y-m-d H:i:s', $_SERVER['REQUEST_TIME']),
    );
    exit(json_encode($result));
}

/**
 * 创建生成token
 * @method buildRandStr
 * @author chengzhigang
 * @param  $n 数字 默认4
 * @return token
 */
function buildRandStr($n = 4)
{
    $chars = array(
        "A", "B", "C", "D", "E", "F", "G",
        "H", "I", "J", "K", "L", "M", "N",
        "O", "P", "Q", "R", "S", "T",
        "U", "V", "W", "X", "Y", "Z",
    );
    $charsLen = count($chars) - 1;
    shuffle($chars);
    $output = "";
    for ($i = 0; $i < $n; $i++) {
        $output .= $chars[mt_rand(0, $charsLen)];
    }
    return strtoupper(md5($output));
}

/**
 * 密码加密方法
 * @method encryptPwd
 * @author chengzhigang
 * @param $password
 * @return
 */
function encryptPwd($password)
{
    return md5(sha1(trim($password)));
}
/**
 * 签名算法
 * @method makeSign
 * @author chengzhigang
 * @param $param请求参数 $sign_key签名key
 * @return
 */
function makeSign($param, $sign_key)
{
    ksort($param); //按字典序排序参数
    $string = "";
    foreach ($param as $k => $v) {
        if ($k != "sign" && $v != "" && !is_array($v)) {
            $string .= $k . "=" . $v . "&";
        }
    }
    $string = trim($string, "&");
    //签名步骤二：在string后加入KEY
    $string = $string . "&key=" . $sign_key;
    //签名步骤三：MD5加密
    $string = md5(sha1($string));
    //签名步骤四：所有字符转为大写
    $result = strtoupper($string);
    return $result;
}

/**
 * 验证签名
 * @method checkSign
 * @author chengzhigang
 * @param $param请求参数
 * @return
 */
function checkSign($param)
{
    $sign = $param['sign'];
    unset($param['sign']);
    $result = makeSign($param, Sign_Key);
    if ($sign == $result) {
        return true;
    } else {
        return false;
    }
}

/**
 * 生成错误记录
 * @method write_error_log
 * @author chengzhigang
 * @param $e
 * @return
 */
function write_error_log($e)
{
    if (!empty($e)) {
        $error = array(
            'code' => $e->getCode(),
            'msg' => $e->getMessage(),
            'file' => $e->getFile(),
            'line' => $e->getLine(),
            'create_time' => date('Y-m-d H:i:s'),
        );
        Db::name('error_log')->insert($error);
    }
}

/**
 * 记录管理员登录日志
 * @method write_login_log
 * @author chengzhigang
 * @param id username
 * @return 
 */
function write_login_log($id,$username){
    $login = array(
        'admin_id'=>$id,
        'username'=>$username,
        'login_ip'=>request()->ip(),
        'create_time'=>date('Y-m-d H:i:s')
    );
    Db::name('login_log')->insert($login);
}
/**
 * 阿里云发送短信
 * @method send_sms
 * @author chengzhigang
 * @param $phone $code
 * @return
 */
function send_sms($phone, $code)
{
    require_once Env::get('extend_path') . '/aliyunSms/aliyun-php-sdk-core/Config.php';
    require_once Env::get('extend_path') . '/aliyunSms/Dysmsapi/Request/V20170525/SendSmsRequest.php';
    //此处需要替换成自己的AK信息
    $accessKeyId = "LTAIyP1GilaFkIBO";
    $accessKeySecret = "6f43QxKhHseRUlISeiUvU0AlwvKjRP";
    //短信API产品名
    $product = "Dysmsapi";
    //短信API产品域名
    $domain = "dysmsapi.aliyuncs.com";
    //暂时不支持多Region
    $region = "cn-hangzhou";

    //初始化访问的acsCleint
    $profile = \DefaultProfile::getProfile($region, $accessKeyId, $accessKeySecret);
    \DefaultProfile::addEndpoint("cn-hangzhou", "cn-hangzhou", $product, $domain);
    $acsClient = new \DefaultAcsClient($profile);

    $request = new \Dysmsapi\Request\V20170525\SendSmsRequest;
    //必填-短信接收号码
    $request->setPhoneNumbers($phone);
    //必填-短信签名
    $request->setSignName("品器");
    //必填-短信模板Code
    $request->setTemplateCode("SMS_138490053");
    //选填-假如模板中存在变量需要替换则为必填(JSON格式)
    $request->setTemplateParam("{\"code\":\"$code\"}");

    //发起访问请求
    $acsResponse = $acsClient->getAcsResponse($request);
    return $acsResponse;
}

function upload($file)
{
    Db::startTrans();
    try {
        // 移动到框架应用根目录/public/uploads/ 目录下 10*1024*1024B(字节) = 100MB
        $extension = strtolower(pathinfo($file->getInfo('name'), PATHINFO_EXTENSION));
        $catalog = '/uploads/' . $extension . '/';
        $re = $file->validate(['size' => 104857600])->move(Env::get('root_path') . 'public' . $catalog);
        if ($re) {
            //上传成功
            $path = $catalog . $re->getSaveName();
            $data = array(
                'name' => $re->getInfo('name'),
                'path' => str_replace('\\', '/', $path),
                'pathurl' => File_Path . str_replace('\\', '/', $path),
                'size' => $re->getSize(),
                'ext' => $re->getExtension(),
                'md5' => $file->hash('md5'),
                'create_time' => date('Y-m-d H:i:s'),
            );
            Db::name('file_upload')->insert($data);
        } else {
					 throw new \Exception($file->getError());
        }
        Db::commit();
    } catch (\Exception $e) {
        Db::rollback();
        write_error_log($e); //记录错误日志
        return array('status' => 1, 'msg' => '上传失败', 'data' => []);
		}
		return array('status' => 0, 'msg' => '上传成功', 'data' => $data);

}

function uploads($files)
{
    //多文件上传
    Db::startTrans();
    try {
        $result = array();
        foreach ($files as $k => $file) {
            if (!empty($file)) {
                // 移动到框架应用根目录/public/uploads/ 目录下 10*1024*1024B(字节) = 100MB
                $extension = strtolower(pathinfo($file->getInfo('name'), PATHINFO_EXTENSION));
                $catalog = '/uploads/' . $extension . '/';
                $re = $file->validate(['size' => 104857600])->move(Env::get('root_path') . 'public' . $catalog);
                if ($re) {
                    //上传成功
                    $path = $catalog . $re->getSaveName();
                    $data = array(
                        'name' => $re->getInfo('name'),
                        'path' => str_replace('\\', '/', $path),
                        'pathurl' => File_Path . str_replace('\\', '/', $path),
                        'size' => $re->getSize(),
                        'ext' => $re->getExtension(),
                        'md5' => $file->hash('md5'),
                        'create_time' => date('Y-m-d H:i:s'),
                    );
                    Db::name('file_upload')->insert($data);
                    $result[$k] = $data;
                } else {
                    throw new \Exception($file->getError());
                }
            }
        }
        Db::commit();
    } catch (\Exception $e) {
        Db::rollback();
        write_error_log($e); //记录错误日志
        return array('status' => 1, 'msg' => '上传失败', 'data' => []);
    }
    return array('status' => 0, 'msg' => '上传成功', 'data' => $result);
}

/**
 * 获取管理员权限
 * @method get_side_navs
 * @author chengzhigang
 * @param 
 * @return 
 */
function get_side_navs($admin_id){
    $data = [];
    $navs_arr = [];
    $admin_navs = Db::name('admin_role a')->join('admin_user b','a.id=b.role_id')->where('b.id',$admin_id)->value('a.navs');
    $navs = Db::name('side_nav')->where('level','between','1,2')->field('id,name,icon,href,pid,level')->order('sort')->select();
    foreach($navs as $k=>$nav){
        $navs_arr[$nav['id']] = $nav;
    }
    if(empty($admin_navs)){
        apiReturn('您没有权限登录平台'); 
    }else{
        $admin_arr = explode(',',$admin_navs);
        foreach($admin_arr as $val){
            if(isset($navs_arr[$val])){
                if($navs_arr[$val]['level']==1){
                    if(!isset($data[$val])){
                        $data[$val] = $navs_arr[$val];
                    }else{
                        $data[$val]['id'] = $navs_arr[$val]['id'];
                        $data[$val]['href'] = $navs_arr[$val]['href'];
                        $data[$val]['name'] = $navs_arr[$val]['name'];
                        $data[$val]['level'] = $navs_arr[$val]['level'];
                        $data[$val]['icon'] = $navs_arr[$val]['icon'];
                        $data[$val]['pid'] = $navs_arr[$val]['pid'];
                    }
                }elseif($navs_arr[$val]['level']==2){
                    $navs_arr[$val]['href'] = !empty($navs_arr[$val]['href'])?url($navs_arr[$val]['href']):'';
                    if(!isset($data[$navs_arr[$val]['pid']]['child'])){
                        $data[$navs_arr[$val]['pid']]['child'] = [];
                    }
                    $data[$navs_arr[$val]['pid']]['child'][] = $navs_arr[$val];
                }
            }
        }
    }
    return array_values($data);
}


function createQrcode($url,$logo=false,$textName=false){
    //第一步：把字符串转换生成二维码图片
    header('Content-type: image/png');
    $value = $url;         //二维码内容
    $errorCorrectionLevel = 'H';  //容错级别
    $matrixPointSize = 6;      //生成图片大小
    $fileName = 'uploads/qrcode/'.md5(microtime(true)).'.png';
    $QR_temp = 'qrcode.png';
    QRcode::png($value,$fileName, $errorCorrectionLevel, $matrixPointSize, 2);
    $QR = imagecreatefromstring(file_get_contents($fileName));
    //第二步：把LOGO图片插入到二维码图片正中间
    // $logo = Env::get('root_path').'public/static/logo.png'; //你的LOGO图片
    if ($logo) {
        $logo = imagecreatefromstring(file_get_contents($logo));  //源图象连接资源。
        $QR_width = imagesx($QR);      //二维码图片宽度
        $QR_height = imagesy($QR);     //二维码图片高度
        $logo_width = imagesx($logo);    //logo图片宽度
        $logo_height = imagesy($logo);   //logo图片高度
        $logo_qr_width = $QR_width / 4;   //组合之后logo的宽度(占二维码的1/5)
        $scale = $logo_width/$logo_qr_width;  //logo的宽度缩放比(本身宽度/组合后的宽度)
        $logo_qr_height = $logo_height/$scale; //组合之后logo的高度
        $from_width = ($QR_width - $logo_qr_width) / 2;  //组合之后logo左上角所在坐标点
        //重新组合图片并调整大小
        //imagecopyresampled() 将一幅图像(源图象)中的一块正方形区域拷贝到另一个图像中
        imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,$logo_qr_height, $logo_width, $logo_height);
        imagedestroy($logo);
    }
    if($textName){
        $size = 30; //字体大小
        $font = Env::get('root_path')."public/water/font/font.otf"; //字体类型,本例为微软雅黑
        $text = $textName; //logo图片要显示的文字内容
        $img = imagecreatetruecolor(300,400);//创建一个长为160高为60的空白图片
        // $black = imagecolorallocate($img, 0, 0, 0); //设置字体颜色
        //2. 先分配一个绿色
        $background = imagecolorallocate($img, 0, 0,255);
		imagefill($img, 0, 0, $background);
        //3. 使用绿色填充画布
        // imagefill($QR, 0, 0, $green);

        // //4. 在画布中绘制图像
        // $bai = imagecolorallocate($QR, 22, 153, 0);
        //使用指定的字体文件绘制文字
        //参数2：字体大小
        //参数3：字体倾斜的角度
        //参数4、5：文字的x、y坐标
        //参数6：文字的颜色
        //参数7：字体文件
        //参数8：绘制的文字
        //$text = iconv("gb2312", "utf-8", $text);
        $content = "";
        $linewidth = 0;
        $width = 200;
        for ($i = 0, $j = mb_strlen($text, "utf-8"); $i < $j; $i++) {
            $curchar = mb_substr($text, $i, 1, "UTF-8");
            $testbox = imagettfbbox($size, 0, $font, $curchar);
            dump($testbox);
            if (($linewidth + $testbox[2]) > $width) {
                $content .= "\n";
                $content .= $curchar;
                $linewidth = $testbox[2];
                dump(true);
                dump($linewidth);
            }
            else {
                $content .= $curchar;
                $linewidth += $testbox[2];
                dump(false);
                dump($linewidth);
            }
        }
        dump($linewidth);
        imagettftext($QR, $size, 0,30, 50, $background, $font, $content); //将文字写到图片中
    }
    //1.生成JPG格式：用imagejpeg()函数 2.生成PNG格式：用imagepng()函数 3.生成GIF格式：用imagegif()函数
    if (imagepng($QR,$QR_temp)) {
        imagedestroy($QR);
        unlink($fileName);
        $image = '<img src="'.$QR_temp.'" >';
        return ['status'=>0,'msg'=>'生成二维码成功','data'=>$image];
    } else {
        return ['status'=>1,'msg'=>'生成二维码失败','data'=>''];
    }
}
